package com.poly.common.core.validate;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import com.poly.common.core.tools.utils.RegexUtil;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.lang.reflect.Field;
import java.util.Map;

public class BeanValidUtils {
    /**
     * 判断对象属性是否为空并返回注解内容
     *
     * @param o 验证对象
     * @return 验证message
     */
    public static String valida(Object o) {
        Field[] fields = ReflectUtil.getFields(o.getClass());
        for (Field field : fields) {
            NotBlank notBlank = field.getAnnotation(NotBlank.class);
            Pattern pattern = field.getAnnotation(Pattern.class);
            if (notBlank == null && pattern == null) {
                continue;
            }
            String filedName = field.getName();
            Map<String, Object> importDeviceMap = BeanUtil.beanToMap(o);
            Object value = importDeviceMap.get(filedName);
            if (notBlank != null) {
                if (value == null || StringUtils.isEmpty(value.toString())) {
                    return notBlank.message();
                }
            }
            if (pattern != null) {
                if (!RegexUtil.match(pattern.regexp(), value.toString())) {
                    return pattern.message();
                }
            }
        }
        return "";
    }
}
